package com.mikepenz.app.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.Toast;

import com.mikepenz.app.R;
import com.mikepenz.app.activity.card.MyCardActivty;
import com.mikepenz.app.activity.login.LoginActivity;
import com.mikepenz.app.activity.message.MessageActivity;
import com.mikepenz.app.activity.until.PageIndicatorActivity;
import com.mikepenz.bean.UserBean;
import com.mikepenz.google_material_typeface_library.GoogleMaterial;
import com.mikepenz.iconics.IconicsDrawable;
import com.mikepenz.iconics.typeface.FontAwesome;
import com.mikepenz.materialdrawer.Drawer;
import com.mikepenz.materialdrawer.DrawerBuilder;
import com.mikepenz.materialdrawer.accountswitcher.AccountHeader;
import com.mikepenz.materialdrawer.accountswitcher.AccountHeaderBuilder;
import com.mikepenz.materialdrawer.model.PrimaryDrawerItem;
import com.mikepenz.materialdrawer.model.ProfileDrawerItem;
import com.mikepenz.materialdrawer.model.ProfileSettingDrawerItem;
import com.mikepenz.materialdrawer.model.SectionDrawerItem;
import com.mikepenz.materialdrawer.model.interfaces.IDrawerItem;
import com.mikepenz.materialdrawer.model.interfaces.IProfile;
import com.mikepenz.materialdrawer.model.interfaces.Nameable;
import com.mikepenz.utils.CookicUntil;
import com.nineoldandroids.animation.Animator;
import com.nineoldandroids.animation.ObjectAnimator;
import com.quickdv.activity.fragment.BaseFragment;
import com.umeng.update.UmengUpdateAgent;

import java.util.Date;


/**
 * 操作首页，主要为展示地图上的TCW信息
 * *
 */
public class MainActivity extends AppCompatActivity implements BaseFragment.OnFragmentInteractionListener {
    private static final int PROFILE_SETTING = 1;
    private Drawer result = null;
    private String userName = "";
    private String userCode = "点击此处登录";
    AccountHeader headerResult = null;
    protected MenuItem refreshItem;
    Toolbar toolbar;


    public void setTitle(String title) {
        getSupportActionBar().setTitle(title);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //supportRequestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sample_nontranslucent);
        // Handle Toolbar
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        initUMeng();
    }

    public void initUMeng() {
        UmengUpdateAgent.update(this);
        UmengUpdateAgent.setUpdateOnlyWifi(false);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_refresh) {
            showRefreshAnimation(item);
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    private void showRefreshAnimation(MenuItem item) {
        hideRefreshAnimation();

        refreshItem = item;

        //这里使用一个ImageView设置成MenuItem的ActionView，这样我们就可以使用这个ImageView显示旋转动画了
        ImageView refreshActionView = (ImageView) getLayoutInflater().inflate(R.layout.action_view, null);
        refreshItem.setActionView(refreshActionView);

        //显示刷新动画
//        Animation animation = AnimationUtils.loadAnimation(this, anim.refresh);
        ObjectAnimator animation = ObjectAnimator.ofFloat(refreshActionView, "rotation", 0f, 360f);
        animation.setDuration(1000);
        animation.setInterpolator(new LinearInterpolator());
//        animation.setRepeatMode(Animation.RESTART);
        animation.setRepeatCount(10);
        animation.start();
        animation.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {

            }

            @Override
            public void onAnimationEnd(Animator animation) {
                hideRefreshAnimation();
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
    }

    private void hideRefreshAnimation() {
        if (refreshItem != null) {
            View view = refreshItem.getActionView();
            if (view != null) {
                view.clearAnimation();
                refreshItem.setActionView(null);
            }
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        //add the values which need to be saved from the drawer to the bundle
        outState = result.saveInstanceState(outState);
        outState = headerResult.saveInstanceState(outState);
        super.onSaveInstanceState(outState);
    }


    Long temp_time = Long.valueOf(0);

    @Override
    public void onBackPressed() {

        Date dt = new Date();
        Long time = dt.getTime();

        //handle the back press :D close the drawer first and if the drawer is closed close the activity
        if (result != null && result.isDrawerOpen()) {
            result.closeDrawer();
        } else {

                if (time - temp_time < 1000) {
                    super.onBackPressed();
                    return;
                } else {
                    Toast.makeText(this, "再次点击退出", Toast.LENGTH_LONG).show();
                    temp_time = time;
                }

        }
    }

    @Override
    public void onFragmentInteraction(Uri uri) {

    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
    }

    public void initView(Bundle savedInstanceState) {
        final IProfile profile = new ProfileDrawerItem()
                .withName(userName).withEmail(userCode);

        headerResult = new AccountHeaderBuilder()
                .withActivity(this)
                .withHeaderBackground(R.drawable.header)
                .addProfiles(
//                        profile,
                        //don't ask but google uses 14dp for the add account icon in gmail but 20dp for the normal icons (like manage account)
                        new ProfileSettingDrawerItem().withName("添加新的账号").withIcon(new IconicsDrawable(this, GoogleMaterial.Icon.gmd_add).actionBarSize().paddingDp(5).colorRes(R.color.material_drawer_primary_text)).withIdentifier(PROFILE_SETTING)

                ).withOnAccountHeaderSelectionViewClickListener(new AccountHeader.OnAccountHeaderSelectionViewClickListener() {
                    @Override
                    public boolean onClick(View view, IProfile iProfile) {
                        if (iProfile.getIdentifier() == PROFILE_SETTING) {
                            Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                            startActivity(intent);
                        }
                        return false;
                    }
                }).withOnAccountHeaderListener(new AccountHeader.OnAccountHeaderListener() {
                    @Override
                    public boolean onProfileChanged(View view, IProfile iProfile, boolean b) {
                        if (iProfile.getIdentifier() == PROFILE_SETTING) {
                            Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                            startActivity(intent);
                        }
                        return false;
                    }
                })
                .withSavedInstance(savedInstanceState)
                .build();

        // Create a few sample profile
        result = new DrawerBuilder(this)
                .withRootView(R.id.drawer_container)
                .withToolbar(toolbar)
                .withAccountHeader(headerResult)
                .withActionBarDrawerToggleAnimated(true)
                .addDrawerItems(
                        new SectionDrawerItem().withName(R.string.drawer_item_open_source),
                        new PrimaryDrawerItem().withName(R.string.drawer_item_home).withIcon(FontAwesome.Icon.faw_paypal),
                        new PrimaryDrawerItem().withName(R.string.drawer_item_free_play).withIcon(FontAwesome.Icon.faw_bar_chart),
                        new PrimaryDrawerItem().withName(R.string.drawer_item_custom).withIcon(FontAwesome.Icon.faw_truck),
                        new SectionDrawerItem().withName(R.string.drawer_item_contact),
                        new PrimaryDrawerItem().withName(R.string.drawer_item_section_header).withIcon(FontAwesome.Icon.faw_money),
//                                .withBadge("0.00元"),
                        new PrimaryDrawerItem().withName(R.string.drawer_item_settings).withIcon(FontAwesome.Icon.faw_envelope_o)
//                        ,new PrimaryDrawerItem().withName(R.string.drawer_item_contact).withIcon(FontAwesome.Icon.faw_cog)
                )
                .withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
                    @Override
                    public boolean onItemClick(AdapterView<?> parent, View view, int position, long id, IDrawerItem drawerItem) {
                        if (drawerItem instanceof Nameable) {
//                            Toast.makeText(SimpleNonTranslucentDrawerActivity.this, SimpleNonTranslucentDrawerActivity.this.getString(((Nameable) drawerItem).getNameRes()), Toast.LENGTH_SHORT).show();

                            if (CookicUntil.getUser().getUserId() == null) {
                                Toast.makeText(MainActivity.this, "用户未登录，请登录", Toast.LENGTH_LONG).show();
                                return false;
                            }
                            Intent intent = new Intent();
                            switch (position) {
                                case 1:
                                    if (CookicUntil.getLatLng() == null) {
                                        Toast.makeText(MainActivity.this, "定位失败，请重试定位", Toast.LENGTH_LONG).show();
                                        return false;
                                    }
                                    intent.setClass(MainActivity.this, ParkListActivity.class);
                                    Bundle bundle = new Bundle();
                                    bundle.putDouble("lat", CookicUntil.getLatLng().latitude);
                                    bundle.putDouble("lng", CookicUntil.getLatLng().longitude);
                                    intent.putExtras(bundle);
                                    startActivity(intent);
                                    break;

                                case 2:
                                    intent.setClass(MainActivity.this, PageIndicatorActivity.class);
                                    startActivity(intent);
                                    break;

                                case 3:
                                    intent.setClass(MainActivity.this, CurrentCarActivity.class);
                                    startActivity(intent);
                                    break;
                                case 5:
                                    intent.setClass(MainActivity.this, MyCardActivty.class);
                                    startActivity(intent);
                                    break;

                                case 6:
                                    intent.setClass(MainActivity.this, MessageActivity.class);
                                    startActivity(intent);
                                    break;

//                                case 7:
//                                    intent.setClass(MainActivity.this, SettingActivity.class);
//                                    startActivity(intent);
//                                    break;

                            }
//                            Toast.makeText(SimpleNonTranslucentDrawerActivity.this, String.valueOf(position), Toast.LENGTH_SHORT).show();

                        }
                        return false;


                    }
                })
//                .withSavedInstance(savedInstanceState)
                .build();

        result.setSelectionByIdentifier(10, false);
        headerResult.setActiveProfile(profile);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (CookicUntil.getUser().getUserId() == null) {
            userName = "分时租用";
            userCode = "点击此处登陆";
        } else {
            userName = CookicUntil.getUser().getRealName();
            userCode = CookicUntil.getUser().getTel();
        }
        initView(null);
    }

    @Override
    protected void onDestroy() {
        CookicUntil.setUser(new UserBean());
        super.onDestroy();
    }


}
